package com.swf.seed.os.execute;

import java.util.Arrays;

import org.apache.commons.cli.ParseException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.swf.seed.os.command.ICommand;
import com.swf.seed.util.SdPatternUtils;

public class Execute {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("springContext-os.xml");
		doit(ac,args);
		ac.close();
	}
	
	public static void doit(ClassPathXmlApplicationContext ac,String[] args){
		try {
			if (args.length == 0) {
				System.out.println("args length = 0");
			}
			String commandName = null;
			String[] commandArgs = null;
			if (!args[0].matches("[a-z]+")) {
				String commandLine = args[0];
				commandName = SdPatternUtils.matchedFirstOne(commandLine,
						"[a-z]+");
				commandArgs = Arrays.copyOfRange(commandLine.split("\\s+"), 1,
						commandLine.split("\\s+").length);
			} else {
				commandName = args[0];
				commandArgs = Arrays.copyOfRange(args, 1, args.length);
			}

			try {
				ICommand bean = ac.getBean(commandName, ICommand.class);
				bean.execute(commandArgs);
			} catch (ParseException e) {
				System.err
						.println("Parsing failed.  Reason: " + e.getMessage());
			}

		} catch (Exception e) {
			System.err
			.println("failed.  Reason: " + e.getMessage());
		}

	}
}
